import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../api/api_service.dart';
import '../../models/pet.dart';
import '../../models/post.dart';
import '../../models/video.dart';
import '../../providers/app_state.dart';
import '../../config/app_theme.dart';
import '../adoption/pet_detail_screen.dart';
import '../community/post_detail_screen.dart';
import '../videos/video_detail_screen.dart';

class HistoryScreen extends StatefulWidget {
  @override
  _HistoryScreenState createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> with SingleTickerProviderStateMixin {
  final ApiService _apiService = ApiService();
  late TabController _tabController;
  List<Pet> _viewedPets = [];
  List<Post> _viewedPosts = [];
  List<Video> _viewedVideos = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadHistoryData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadHistoryData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final appState = Provider.of<AppState>(context, listen: false);

      final petIds = appState.recentlyViewedPets;
      final postIds = appState.recentlyViewedPosts;
      final videoIds = appState.recentlyViewedVideos;

      // 只有当有浏览记录时才加载数据
      if (petIds.isNotEmpty) {
        final allPets = await _apiService.getPets(limit: 100);
        _viewedPets = allPets
            .where((pet) => petIds.contains(pet.id))
            .toList()
            // 按照浏览顺序排序
            ..sort((a, b) => petIds.indexOf(a.id).compareTo(petIds.indexOf(b.id)));
      }

      if (postIds.isNotEmpty) {
        final allPosts = await _apiService.getPosts(limit: 100);
        _viewedPosts = allPosts
            .where((post) => postIds.contains(post.id))
            .toList()
            ..sort((a, b) => postIds.indexOf(a.id).compareTo(postIds.indexOf(b.id)));
      }

      if (videoIds.isNotEmpty) {
        final allVideos = await _apiService.getVideos(limit: 100);
        _viewedVideos = allVideos
            .where((video) => videoIds.contains(video.id))
            .toList()
            ..sort((a, b) => videoIds.indexOf(a.id).compareTo(videoIds.indexOf(b.id)));
      }

      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading history data: $e');
    }
  }

  void _clearPetHistory() {
    final appState = Provider.of<AppState>(context, listen: false);
    appState.recentlyViewedPets.clear();
    setState(() {
      _viewedPets.clear();
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已清空宠物浏览记录')),
    );
  }

  void _clearPostHistory() {
    final appState = Provider.of<AppState>(context, listen: false);
    appState.recentlyViewedPosts.clear();
    setState(() {
      _viewedPosts.clear();
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已清空帖子浏览记录')),
    );
  }

  void _clearVideoHistory() {
    final appState = Provider.of<AppState>(context, listen: false);
    appState.recentlyViewedVideos.clear();
    setState(() {
      _viewedVideos.clear();
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已清空视频浏览记录')),
    );
  }

  void _navigateToPetDetail(Pet pet) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PetDetailScreen(pet: pet),
      ),
    ).then((_) {
      // 回到历史页面后重新加载数据
      _loadHistoryData();
    });
  }

  void _navigateToPostDetail(Post post) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PostDetailScreen(post: post),
      ),
    ).then((_) {
      _loadHistoryData();
    });
  }

  void _navigateToVideoDetail(Video video) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => VideoDetailScreen(video: video),
      ),
    ).then((_) {
      _loadHistoryData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('浏览历史'),
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            Tab(text: '宠物'),
            Tab(text: '帖子'),
            Tab(text: '视频'),
          ],
        ),
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : TabBarView(
              controller: _tabController,
              children: [
                _buildPetHistoryTab(),
                _buildPostHistoryTab(),
                _buildVideoHistoryTab(),
              ],
            ),
    );
  }

  Widget _buildPetHistoryTab() {
    if (_viewedPets.isEmpty) {
      return _buildEmptyView('暂无宠物浏览记录');
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '共浏览 ${_viewedPets.length} 个宠物',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
              ),
              TextButton.icon(
                icon: Icon(Icons.delete_outline, size: 16),
                label: Text('清空'),
                onPressed: _clearPetHistory,
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            padding: EdgeInsets.all(8.0),
            itemCount: _viewedPets.length,
            itemBuilder: (context, index) {
              final pet = _viewedPets[index];
              return _buildPetHistoryItem(pet);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildPostHistoryTab() {
    if (_viewedPosts.isEmpty) {
      return _buildEmptyView('暂无帖子浏览记录');
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '共浏览 ${_viewedPosts.length} 个帖子',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
              ),
              TextButton.icon(
                icon: Icon(Icons.delete_outline, size: 16),
                label: Text('清空'),
                onPressed: _clearPostHistory,
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            padding: EdgeInsets.all(8.0),
            itemCount: _viewedPosts.length,
            itemBuilder: (context, index) {
              final post = _viewedPosts[index];
              return _buildPostHistoryItem(post);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildVideoHistoryTab() {
    if (_viewedVideos.isEmpty) {
      return _buildEmptyView('暂无视频浏览记录');
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '共浏览 ${_viewedVideos.length} 个视频',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
              ),
              TextButton.icon(
                icon: Icon(Icons.delete_outline, size: 16),
                label: Text('清空'),
                onPressed: _clearVideoHistory,
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            padding: EdgeInsets.all(8.0),
            itemCount: _viewedVideos.length,
            itemBuilder: (context, index) {
              final video = _viewedVideos[index];
              return _buildVideoHistoryItem(video);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildEmptyView(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.history,
            size: 64,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16),
          Text(
            message,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPetHistoryItem(Pet pet) {
    return ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
      leading: ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: Image.network(
          pet.images.first,
          width: 60,
          height: 60,
          fit: BoxFit.cover,
        ),
      ),
      title: Text(
        pet.name,
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
      subtitle: Text(
        '${pet.species} · ${pet.breed} · ${pet.age}岁',
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey[600],
        ),
      ),
      trailing: Icon(Icons.arrow_forward_ios, size: 16),
      onTap: () => _navigateToPetDetail(pet),
    );
  }

  Widget _buildPostHistoryItem(Post post) {
    return ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
      leading: post.images.isNotEmpty
          ? ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: Image.network(
                post.images.first,
                width: 60,
                height: 60,
                fit: BoxFit.cover,
              ),
            )
          : Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.0),
                color: Colors.grey[200],
              ),
              child: Icon(
                Icons.article,
                color: AppTheme.primaryColor,
              ),
            ),
      title: Text(
        post.title,
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Text(
        '${post.userName} · ${_formatDate(post.createdAt)}',
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey[600],
        ),
      ),
      trailing: Icon(Icons.arrow_forward_ios, size: 16),
      onTap: () => _navigateToPostDetail(post),
    );
  }

  Widget _buildVideoHistoryItem(Video video) {
    return ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
      leading: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Image.network(
              video.coverUrl,
              width: 60,
              height: 60,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            bottom: 4,
            right: 4,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.7),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                _formatDuration(video.duration),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                ),
              ),
            ),
          ),
        ],
      ),
      title: Text(
        video.title,
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Text(
        '${video.userName} · ${_formatNumber(video.views)}次观看',
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey[600],
        ),
      ),
      trailing: Icon(Icons.arrow_forward_ios, size: 16),
      onTap: () => _navigateToVideoDetail(video),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.month}月${date.day}日';
  }

  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '$minutes:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  String _formatNumber(int number) {
    if (number >= 10000) {
      return '${(number / 10000).toStringAsFixed(1)}万';
    } else if (number >= 1000) {
      return '${(number / 1000).toStringAsFixed(1)}千';
    }
    return number.toString();
  }
} 